using System;
using System.Reflection;
using DIoms.Utilities;

namespace Pharmacy.Ultilities
{
	/// <summary>
	/// Summary description for AssemblyFactory.
	/// </summary>
	public class AssemblyFactory
	{
		/// <summary>
		/// Get Type from Assembly
		/// </summary>
		/// <param name="assemblyName">AssemblyName</param>
		/// <param name="typeName">TypeName</param>
		/// <returns>Type from Assembly</returns>
		/// <author></author>
		/// <history>
		/// 2011.01.24 - ThangTran: modified try-catch.
		/// </history>
		public static Type GetTypeFromAssembly(string assemblyName, string typeName)
		{
			Assembly assemblyInstance = null;
			Type typeInstance = null;
			
            // TODO: code not completed, use new Exception: GeneralException()
			try
			{
				assemblyInstance = Assembly.Load(assemblyName);
			}
			catch (Exception ex)
			{
				throw new ApplicationException("Exception occured in Factory while trying to load assembly." + "\r\n" + ex.Message);
			}

			try
			{
				typeInstance = assemblyInstance.GetType(typeName, true, false);
			}
			catch (Exception ex)
			{
				throw new ApplicationException("Exception occured in Factory while trying to get type." + "\r\n" + ex.Message);
			}
			return typeInstance;
		}

		/// <summary>
		/// Create Object
		/// </summary>
		/// <param name="AssemblyName">Assembly Name</param>
		/// <param name="TypeName">Type Name</param>
		/// <param name="Parameter">Parameter value</param>
		/// <returns>object by Assembly</returns>
		public static object CreateObject(string assemblyName, string typeName, string parameter)
		{
			Type t = GetTypeFromAssembly(assemblyName, typeName);
			object o = null;
			if (t!=null)
			{
				o = CreateObject(t, parameter);
			}
			return o;
		}

		/// <summary>
		/// Create Object
		/// </summary>
		/// <param name="type">Type Input</param>
		/// <param name="Parameter">Parameter Input</param>
		/// <returns>object by type</returns>
		public static object CreateObject(Type type, string parameter)
		{
			object o = null;
			if (type != null)
			{
				try
				{
					if (ValidateUtil.IsObjectValid(parameter))
					{
						o = Activator.CreateInstance(type, parameter.Split(",".ToCharArray()));
					}
					else
					{
						o = Activator.CreateInstance(type);
					}
				}
				catch (Exception ex)
				{
					throw new ApplicationException("Exception occured in Factory while trying to create object." + "\r\n" + ex.Message);
				}
			}
			return o;
		}
	}
}
